/**
 * OKR 节点详情弹窗组件
 * 展示节点的详细信息，包括关键结果、进度更新等
 */

import React, { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  Modal,
  Descriptions,
  Progress,
  Avatar,
  Tag,
  Button,
  Space,
  Divider,
  Card,
  InputNumber,
  message,
  Typography
} from "antd";
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  UserOutlined,
  CalendarOutlined,
  AimOutlined,
  TrophyOutlined
} from "@ant-design/icons";
import type { AppDispatch } from "../../../store";
import { updateKeyResult, deleteOKRNode, selectOKRNodes } from "../../../store/okrSlice";
import type { KeyResult, UpdateKeyResultRequest } from "../../../types/okr";
import { OKRNodeType, OKRStatus } from "../../../types/okr";

const { Title, Text } = Typography;

interface OKRNodeDetailModalProps {
  /** 节点ID */
  nodeId: string;
  /** 是否显示弹窗 */
  visible: boolean;
  /** 关闭弹窗回调 */
  onClose: () => void;
}

/**
 * 获取节点类型的显示名称
 */
const getNodeTypeName = (type: OKRNodeType) => {
  switch (type) {
    case OKRNodeType.DEPARTMENT:
      return "部门目标";
    case OKRNodeType.TEAM:
      return "团队目标";
    case OKRNodeType.INDIVIDUAL:
      return "个人目标";
    default:
      return "目标";
  }
};

/**
 * 获取状态的显示名称和颜色
 */
const getStatusInfo = (status: OKRStatus) => {
  switch (status) {
    case OKRStatus.NOT_STARTED:
      return { name: "未开始", color: "default" };
    case OKRStatus.IN_PROGRESS:
      return { name: "进行中", color: "processing" };
    case OKRStatus.COMPLETED:
      return { name: "已完成", color: "success" };
    case OKRStatus.OVERDUE:
      return { name: "已逾期", color: "error" };
    default:
      return { name: "未知", color: "default" };
  }
};

/**
 * 关键结果项组件
 */
const KeyResultItem: React.FC<{
  keyResult: KeyResult;
  nodeId: string;
  onUpdate: () => void;
}> = ({ keyResult, nodeId, onUpdate }) => {
  const dispatch = useDispatch<AppDispatch>();
  const [editing, setEditing] = useState(false);
  const [newValue, setNewValue] = useState(keyResult.currentValue);
  const [updating, setUpdating] = useState(false);

  /**
   * 保存更新
   */
  const handleSave = async () => {
    if (newValue < 0 || newValue > keyResult.targetValue * 1.2) {
      message.error("输入值超出合理范围");
      return;
    }

    setUpdating(true);
    try {
      const updateData: UpdateKeyResultRequest = {
        nodeId,
        keyResultId: keyResult.id,
        currentValue: newValue
      };

      await dispatch(updateKeyResult(updateData)).unwrap();
      message.success("更新成功");
      setEditing(false);
      onUpdate();
    } catch (error) {
      message.error("更新失败");
    } finally {
      setUpdating(false);
    }
  };

  /**
   * 取消编辑
   */
  const handleCancel = () => {
    setNewValue(keyResult.currentValue);
    setEditing(false);
  };

  const statusInfo = getStatusInfo(keyResult.status);

  return (
    <Card size="small" className="mb-3">
      <div className="flex items-start justify-between">
        <div className="flex-1">
          <div className="flex items-center space-x-2 mb-2">
            <Title level={5} className="!mb-0">
              {keyResult.title}
            </Title>
            <Tag color={statusInfo.color}>{statusInfo.name}</Tag>
          </div>

          <Text type="secondary" className="block mb-3">
            {keyResult.description}
          </Text>

          <div className="grid grid-cols-2 gap-4 mb-3">
            <div>
              <Text strong>当前值: </Text>
              {editing ? (
                <InputNumber
                  value={newValue}
                  onChange={value => setNewValue(value || 0)}
                  size="small"
                  style={{ width: 80 }}
                  min={0}
                  max={keyResult.targetValue * 1.2}
                />
              ) : (
                <Text>{keyResult.currentValue}</Text>
              )}
              <Text type="secondary">
                {" "}
                / {keyResult.targetValue} {keyResult.unit}
              </Text>
            </div>
            <div>
              <Text strong>截止时间: </Text>
              <Text>{keyResult.deadline}</Text>
            </div>
          </div>

          <div className="mb-3">
            <div className="flex items-center justify-between mb-1">
              <Text strong>完成进度</Text>
              <Text strong>{keyResult.progress}%</Text>
            </div>
            <Progress
              percent={keyResult.progress}
              strokeColor={keyResult.progress >= 100 ? "#52c41a" : "#1890ff"}
              size="small"
            />
          </div>
        </div>

        <div className="ml-4">
          {editing ? (
            <Space>
              <Button type="primary" size="small" onClick={handleSave} loading={updating}>
                保存
              </Button>
              <Button size="small" onClick={handleCancel}>
                取消
              </Button>
            </Space>
          ) : (
            <Button type="text" icon={<EditOutlined />} size="small" onClick={() => setEditing(true)}>
              更新进度
            </Button>
          )}
        </div>
      </div>
    </Card>
  );
};

/**
 * OKR 节点详情弹窗组件
 */
const OKRNodeDetailModal: React.FC<OKRNodeDetailModalProps> = ({ nodeId, visible, onClose }) => {
  const dispatch = useDispatch<AppDispatch>();
  const nodes = useSelector(selectOKRNodes);
  const [deleting, setDeleting] = useState(false);

  const node = nodes[nodeId];

  if (!node) {
    return null;
  }

  /**
   * 删除节点
   */
  const handleDelete = async () => {
    Modal.confirm({
      title: "确认删除",
      content: `确定要删除"${node.title}"吗？这将同时删除所有子节点。`,
      okText: "删除",
      okType: "danger",
      cancelText: "取消",
      onOk: async () => {
        setDeleting(true);
        try {
          await dispatch(deleteOKRNode(nodeId)).unwrap();
          message.success("删除成功");
          onClose();
        } catch (error) {
          message.error("删除失败");
        } finally {
          setDeleting(false);
        }
      }
    });
  };

  /**
   * 处理关键结果更新
   */
  const handleKeyResultUpdate = () => {
    // 更新后重新渲染，数据会自动从 Redux store 获取最新状态
  };

  const statusInfo = getStatusInfo(node.status);

  return (
    <Modal
      title={
        <div className="flex items-center space-x-2">
          <AimOutlined />
          <span>目标详情</span>
        </div>
      }
      open={visible}
      onCancel={onClose}
      width={800}
      footer={
        <div className="flex justify-between">
          <Space>
            <Button icon={<EditOutlined />} onClick={() => message.info("编辑功能待开发")}>
              编辑目标
            </Button>
            <Button icon={<PlusOutlined />} onClick={() => message.info("添加关键结果功能待开发")}>
              添加关键结果
            </Button>
          </Space>
          <Space>
            <Button danger icon={<DeleteOutlined />} onClick={handleDelete} loading={deleting}>
              删除目标
            </Button>
            <Button onClick={onClose}>关闭</Button>
          </Space>
        </div>
      }
    >
      <div className="space-y-6">
        {/* 基本信息 */}
        <div>
          <Title level={4}>{node.title}</Title>
          <Text type="secondary" className="block mb-4">
            {node.description}
          </Text>

          <Descriptions column={2} size="small">
            <Descriptions.Item label="目标类型">
              <Tag color="blue">{getNodeTypeName(node.type)}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={statusInfo.color}>{statusInfo.name}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="负责人">
              <div className="flex items-center space-x-2">
                <Avatar size="small" src={node.owner.avatar} icon={<UserOutlined />} />
                <span>{node.owner.name}</span>
              </div>
            </Descriptions.Item>
            <Descriptions.Item label="所属季度">
              <Tag>{node.quarter}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="开始时间">
              <div className="flex items-center space-x-1">
                <CalendarOutlined />
                <span>{node.startDate}</span>
              </div>
            </Descriptions.Item>
            <Descriptions.Item label="结束时间">
              <div className="flex items-center space-x-1">
                <CalendarOutlined />
                <span>{node.endDate}</span>
              </div>
            </Descriptions.Item>
          </Descriptions>
        </div>

        <Divider />

        {/* 整体进度 */}
        <div>
          <div className="flex items-center space-x-2 mb-3">
            <TrophyOutlined />
            <Title level={5} className="!mb-0">
              整体进度
            </Title>
          </div>
          <div className="flex items-center space-x-4">
            <Progress
              type="circle"
              percent={node.progress}
              width={80}
              strokeColor={node.progress >= 100 ? "#52c41a" : "#1890ff"}
            />
            <div>
              <div className="text-lg font-semibold">{node.progress}%</div>
              <div className="text-sm text-gray-500">{node.keyResults.length} 个关键结果</div>
            </div>
          </div>
        </div>

        <Divider />

        {/* 关键结果列表 */}
        <div>
          <div className="flex items-center justify-between mb-4">
            <Title level={5} className="!mb-0">
              关键结果
            </Title>
            <Button
              type="dashed"
              icon={<PlusOutlined />}
              size="small"
              onClick={() => message.info("添加关键结果功能待开发")}
            >
              添加关键结果
            </Button>
          </div>

          {node.keyResults.length > 0 ? (
            <div>
              {node.keyResults.map(keyResult => (
                <KeyResultItem
                  key={keyResult.id}
                  keyResult={keyResult}
                  nodeId={nodeId}
                  onUpdate={handleKeyResultUpdate}
                />
              ))}
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              <AimOutlined style={{ fontSize: 48, marginBottom: 16 }} />
              <div>暂无关键结果</div>
              <div className="text-sm">点击上方按钮添加关键结果</div>
            </div>
          )}
        </div>

        {/* 子目标 */}
        {node.children.length > 0 && (
          <>
            <Divider />
            <div>
              <Title level={5} className="!mb-3">
                子目标 ({node.children.length})
              </Title>
              <div className="space-y-2">
                {node.children.map(childId => {
                  const childNode = nodes[childId];
                  if (!childNode) return null;

                  return (
                    <Card key={childId} size="small" className="cursor-pointer hover:shadow-md">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-3">
                          <Avatar size="small" src={childNode.owner.avatar} icon={<UserOutlined />} />
                          <div>
                            <div className="font-medium">{childNode.title}</div>
                            <div className="text-sm text-gray-500">
                              {getNodeTypeName(childNode.type)} · {childNode.owner.name}
                            </div>
                          </div>
                        </div>
                        <div className="text-right">
                          <div className="text-sm font-medium">{childNode.progress}%</div>
                          <Progress percent={childNode.progress} size="small" showInfo={false} style={{ width: 60 }} />
                        </div>
                      </div>
                    </Card>
                  );
                })}
              </div>
            </div>
          </>
        )}
      </div>
    </Modal>
  );
};

export default OKRNodeDetailModal;
